package cn.liyiming.bbs.modular.system.controller;

import cn.liyiming.bbs.core.shiro.ShiroKit;
import cn.liyiming.bbs.modular.system.dao.ArticleMapper;
import cn.liyiming.bbs.modular.system.model.Article;
import cn.liyiming.bbs.modular.system.model.User;
import cn.liyiming.bbs.modular.system.service.IArticleService;
import cn.liyiming.bbs.modular.system.service.IUserService;
import cn.liyiming.bbs.util.AjaxResponse;
import cn.liyiming.bbs.util.SystemException;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program: bbs
 * @description: 社区用户
 * @author: 李一鸣
 * @create: 2020-02-22 16:16
 **/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 初始身份
     */
    public final static String SYSTEM_ROLE = "6";
    /**
     * 初始身份
     */
    public final static int SALT_LENGTH = 5;
    /**
     * 初始状态
     */
    public final static int INIT_STATUS = 1;
    /**
     * 跳转到登录页
     */
    @RequestMapping({"/login"})
    public String login(Model model) {

        return "pages/user/login";
    }


    /**
     * 登录判断并跳转到注册页
     */
    @RequestMapping({"/verifyLogin"})
    @ResponseBody
    public Object index(Model model, User user, HttpSession session, HttpServletResponse response) {

        String username = user.getAccount();
        String password = user.getPassword();
        //获取当前主体
        Subject subject = SecurityUtils.getSubject();
        //封装token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //执行登录操作
        try
        {
            subject.login(token);
            // 为了防止cookie外泄密码的密文，将登录密码置为null
            User userByAccount = userService.getUserByAccount(user.getAccount());
            userByAccount.setPassword(null);
            session.setAttribute("user", userByAccount);
            // sessionid持久化(替换默认cookie有效期 -1)
            Cookie cookie = new Cookie("JSESSIONID", session.getId());

            cookie.setMaxAge(60*60*2);
            // 有效期2hours

            response.addCookie(cookie);
            return AjaxResponse.success(200);
        }
        catch (SystemException e) //抛出这个异常说明用户不存在
        {
            return AjaxResponse.error(e);
        }

    }

    /**
     * 跳转到注册页
     */
    @RequestMapping({"/index"})
    public String userIndex(Model model, HttpSession session,@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer limit) {
        User user = (User)session.getAttribute("user");
        model.addAttribute("user",user);
        Integer id = user.getId();
        List<Article> articles = articleMapper.selectByArtUserId(id);
        PageHelper.startPage(page,limit);
        PageInfo pageInfo = new PageInfo(articles);
        HashMap map = new HashMap(16);
        model.addAttribute("count",pageInfo.getTotal());
        model.addAttribute("limit",limit);
        model.addAttribute("page",page);
        model.addAttribute("articles",pageInfo.getList());
        return "pages/user/index";
    }





    /**
     * 跳转到注册页
     */
    @RequestMapping({"/reg"})
    public String register(Model model) {

        return "pages/user/reg";
    }


    /**
     * 跳转到用户主页
     */
    @RequestMapping({"/home/{userId}"})
    public String homePage(Model model,@PathVariable("userId")Integer userId) {
        User user = userService.selectById(userId);
        user.setPassword(null);
        model.addAttribute("user",user);
        return "pages/user/home";
    }

    /**
     * 跳转到密码找回页
     */
    @RequestMapping({"/forget"})
    public String forgetPass(Model model) {

        return "pages/user/forget";
    }

    /**
     * 跳转到消息页
     */
    @RequestMapping({"/message"})
    public String message(Model model) {

        return "pages/user/message";
    }

    /**
     * 跳转到个人信息设置页
     */
    @RequestMapping({"/set"})
    public String set(Model model) {

        return "pages/user/set";
    }


    /**
     * 跳转到修改
     */
    @RequestMapping("/user_update/{userId}")
    public String userUpdate(@PathVariable Integer id, Model model) {
        User user = userService.selectById(id);
        model.addAttribute("item", user);
        return "user_edit.html";
    }


    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return userService.selectList(null);
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(User user) {

        String randomSalt = ShiroKit.getRandomSalt(SALT_LENGTH);
        user.setSalt(randomSalt);
        String s = ShiroKit.md5(user.getPassword(), randomSalt);
        user.setPassword(s);
        user.setEmail(user.getAccount());
        user.setRoleid(SYSTEM_ROLE);
        user.setCreatetime(new Date());
        user.setStatus(INIT_STATUS);
        userService.insert(user);
        return AjaxResponse.success();
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer userId) {

        userService.deleteById(userId);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(User user) {
        userService.updateById(user);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{id}")
    @ResponseBody
    public Object detail(@PathVariable("id") Integer id) {

        return userService.selectById(id);
    }
}


